package nc.appcan.sp.bs.filelist;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import nc.appcan.sp.nc.vo.FileListResultVO;
import nc.appcan.sp.nc.vo.FileVO;
import nc.appcan.sppub.pub.MAFileAction;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.itf.uap.pf.INCMAFileInter;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;

@MAFileAction("common")
public class NCMABillFileHandler implements INCMAFileInter {

	public int getBillFileCount(String billid, String billtype)
			throws BusinessException {
		BaseDAO dao = new BaseDAO();
		String sql = "select count(1) from sm_pub_filesystem  where path like '%"+billid+"%' and isfolder ='n'";
		Object obj =  dao.executeQuery(sql, new ColumnProcessor());
	    int num = obj ==null?0:(Integer)obj;
		return num;
	}

	public FileListResultVO getBillFileList(String billid, String billtype)
			throws BusinessException {
		BaseDAO  dao = new BaseDAO();
		FileListResultVO  resvo = new FileListResultVO(billid,billtype);
		String sql = "select filelength,path,pk from sm_pub_filesystem  where path like '%"+billid+"%' and isfolder ='n'";
		ArrayList list = (ArrayList)dao.executeQuery(sql, new ArrayListProcessor());
		for (int i = 0; i < list.size(); i++) {
			FileVO  vo = new FileVO();
			Object [] os = (Object [])list.get(i);
			String[] paths = ((String)os[1]).split("/");
			String filename = paths[paths.length-1];
			String[] filetypes = filename.split("\\.");
			String filetype = filetypes[filetypes.length-1];
			vo.setFileid((String)os[2]);
			vo.setFilename(filename);
			vo.setFilepath((String)os[1]);
			vo.setFilesize((String)os[0]);
			vo.setFiletype(filetype);
			resvo.getFilelist().add(vo);
		}
		return resvo;
	}

	public void downloadNC(OutputStream out,String pk)throws BusinessException {
		
		try {
			BaseDAO  dao = new BaseDAO();
			String sql = "select path from sm_pub_filesystem where pk='"+pk+"'";
			String billpath = (String)dao.executeQuery(sql, new ColumnProcessor());
			IFileSystemService service = NCLocator.getInstance().lookup(IFileSystemService.class);
			service.downLoadFile(billpath, out);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
